package org.example.test.tika;

import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.pdf.PDFParser;
import org.apache.tika.sax.BodyContentHandler;
import org.xml.sax.SAXException;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class TikaExample {
    public static String getContent(String filePath){
        File file = new File(filePath);
        String text = null;
        try (InputStream input = new FileInputStream(file)) {
            // 创建解析器上下文和处理类
            ParseContext context = new ParseContext();
            BodyContentHandler handler = new BodyContentHandler();
            Metadata metadata = new Metadata();
            PDFParser pdfParser = new PDFParser();

            // 解析 PDF 文件，提取文本和元数据
            pdfParser.parse(input, handler, metadata, context);

            // 获取文本内容
            text = handler.toString();
//            System.out.println("Text Content:\n" + text);

            // 获取元数据信息，例如作者、创建日期等
//            String author = metadata.get(Metadata.AUTHOR);
//            System.out.println("Author: " + author);
//            String creationDate = metadata.get(Metadata.CREATION_DATE);
//            System.out.println("Creation Date: " + creationDate);
//            System.out.println(metadata);
            // 可以继续获取其他元数据...
        } catch (IOException | SAXException | TikaException e) {
            e.printStackTrace();
        }
        return text;
    }
    public static void main(String[] args) {


        String content = TikaExample.getContent("C:\\Users\\Downloads\\SC.pdf");
        System.out.println(content);

    }
}
